import { getBusinessObject } from 'bpmn-js/lib/util/ModelUtil'
import { createModdleElement } from './bpmnPropertyUtils/extensionElements'
import { without } from 'min-dash'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import { getRoot, getCurrentObject, findRootElementsByType } from './bpmnPropertyUtils/eventDefinition'

export function getGlobalReferenceOptions(element, type) {
  const result = []
  const data = findRootElementsByType(getBusinessObject(element), type)
  data.forEach((item: any) => {
    result.push({
      value: item.get('id'),
      label: item.get('name')
    })
  })
  return result
}

export function getGlobalReference(element, type) {
  return findRootElementsByType(getBusinessObject(element), type)
}

export function addGlobalReference(element, type, props) {
  const modeling = useModelerStore().getModeling
  const root = getRoot(getCurrentObject(element, type))
  const globalReference = createModdleElement(type, props, root)
  modeling.updateModdleProperties(element, root, { rootElements: [...root.get('rootElements'), globalReference] })
}

export function editGlobalReference(element, type, props, index) {
  const modeling = useModelerStore().getModeling
  const data = findRootElementsByType(getBusinessObject(element), type)
  data[index].id = props.id
  data[index].name = props.name
  if (type === 'bpmn:Error') {
    data[index].errorCode = props.errorCode
    data[index].errorMessage = props.errorMessage
  }
  const root = getRoot(getCurrentObject(element, type))
  modeling.updateModdleProperties(element, root, { rootElements: data })
}

export function removeGlobalReference(element, type, props) {
  const modeling = useModelerStore().getModeling
  const root = getRoot(getCurrentObject(element, type))
  const data = findRootElementsByType(getBusinessObject(element), type)
  const newData = without(data, props)
  modeling.updateModdleProperties(element, root, { rootElements: newData })
}
